package com.bawei.module_publish.openlive.adapter
import android.annotation.SuppressLint
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.bawei.module_publish.R
import com.bumptech.glide.Glide
// 广告数据类
data class AdItem(
    val id: Int,
    val desc: String,
    val imgUrl: String
)

class AdSelectAdapter(
    private val adList: List<AdItem>,
    private val onAdSelected: (AdItem) -> Unit
) : RecyclerView.Adapter<AdSelectAdapter.AdViewHolder>() {

    private var selectedPosition = -1

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): AdViewHolder {
        val view = LayoutInflater.from(parent.context)
            .inflate(R.layout.item_ad_select, parent, false)
        return AdViewHolder(view)
    }

    override fun onBindViewHolder(holder: AdViewHolder, @SuppressLint("RecyclerView") position: Int) {
        val ad = adList[position]
        holder.tvAdDesc.text = ad.desc
        Glide.with(holder.itemView)
            .load(ad.imgUrl)
            .into(holder.ivAdImg)

        // 单选状态
        if (selectedPosition == position) {
            holder.ivAdSelect.setImageResource(R.drawable.baseline_radio_button_checked_24)
        } else {
            holder.ivAdSelect.setImageResource(R.drawable.baseline_radio_button_unchecked_24)
        }

        // 点击item或选中图标都可选中
        holder.itemView.setOnClickListener {
            if (selectedPosition != position) {
                val oldPos = selectedPosition
                selectedPosition = position
                notifyItemChanged(oldPos)
                notifyItemChanged(selectedPosition)
                onAdSelected(ad)
            }
        }
        holder.ivAdSelect.setOnClickListener {
            if (selectedPosition != position) {
                val oldPos = selectedPosition
                selectedPosition = position
                notifyItemChanged(oldPos)
                notifyItemChanged(selectedPosition)
                onAdSelected(ad)
            }
        }
    }

    override fun getItemCount(): Int = adList.size

    fun getSelectedAd(): AdItem? =
        if (selectedPosition in adList.indices) adList[selectedPosition] else null

    class AdViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        val ivAdImg: ImageView = itemView.findViewById(R.id.ivAdImg)
        val tvAdDesc: TextView = itemView.findViewById(R.id.tvAdDesc)
        val ivAdSelect: ImageView = itemView.findViewById(R.id.ivAdSelect)
    }
}